use crate::components::Counter;
use crate::state::{Action, Event, State};
use log::trace;
use yew::prelude::*;
use yew_store::StoreLink;

pub struct Model {
    store: StoreLink<State, Action>,
    value: isize,
}

pub enum Msg {
    IncrementSelf,
    DecrementSelf,
    IncrementState,
    DecrementState,

    StoreEvent(Event),
}

#[derive(Properties)]
pub struct Props {
    #[props(required)]
    pub store: StoreLink<State, Action>,
}

impl Component for Model {
    type Message = Msg;
    type Properties = Props;

    fn create(props: Self::Properties, mut link: ComponentLink<Self>) -> Self {
        // Store事件处理回调函数
        let callback = link.send_back(|event| Msg::StoreEvent(event));
        Model {
            value: 0,
            store: props.store.reform(Some(callback)),
            // store: connect_to_store(None), // 如果不想订阅Store事件，这里传入None就可以了。
        }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::StoreEvent(event) => return self.handle(event),
            Msg::IncrementSelf => {
                trace!("self plus one");
                self.value += 1;
            }
            Msg::DecrementSelf => {
                trace!("self minus one");
                self.value -= 1;
            }
            Msg::IncrementState => {
                trace!("state plus one");
                self.store.send(Action::CounterInc);
            }
            Msg::DecrementState => {
                trace!("state minus one");
                self.store.send(Action::CounterDec);
            }
        }
        true
    }
}
impl Model {
    fn handle(&mut self, event: Event) -> ShouldRender {
        trace!("{:?}", event);
        false
    }
}

impl Renderable<Model> for Model {
    fn view(&self) -> Html<Self> {
        html! {
            <div class="box">
                <h3 class="has-text-centered has-text-weight-bold">{"local counter"}</h3>
                <Counter value=self.value onincrement=|_| Msg::IncrementSelf  ondecrement=|_| Msg::DecrementSelf />
                <h3 class="has-text-centered has-text-weight-bold">{"global counter"}</h3>
                // 使用 store.state() 访问全局状态对象
                <Counter value=self.store.state().counter onincrement=|_| Msg::IncrementState  ondecrement=|_| Msg::DecrementState />
            </div>
        }
    }
}
